<template>
  <view>
    <cu-custom bgColor="bg-gradual-green" :isBack="true">
      <block slot="backText">返回</block>
      <block slot="right">
        <view class="u-m-r-40" @tap="toAdd">新增记录</view>
      </block>
    </cu-custom>

    <view class="wrap">
      <!-- 查询系列 -->
      <view class="cu-bar search bg-white">
        <view style="width: 100%; padding: 0 20rpx 0 20rpx">
          <u-search
            class="search-width"
            shape="round"
            placeholder="模糊搜索账单名称"
            v-model="name"
            :show-action="false"
            @clear="change"
            @custom="change"
            @search="change"
          ></u-search>
        </view>
      </view>

      <view class="u-flex u-flex-nowrap picker-border">
        <view
          @tap="calendarShow = true"
          class="u-m-l-40 u-font-30"
          style="margin-right: auto; justify-content: flex-start"
        >
          {{ startInput ? startInput : startNowTime }}
        </view>
        <view style="justify-content: center">-</view>
        <view
          @tap="calendarShow = true"
          class="u-m-r-40 u-font-30"
          style="margin-left: auto; justify-content: flex-end"
        >
          {{ endInput ? endInput : endNowTime }}
        </view>
      </view>

      <view class="u-flex u-row-center">
        <u-dropdown
          :close-on-click-mask="mask"
          ref="uDropdown"
          :activeColor="activeColor"
          :borderBottom="false"
          @close="closeChange"
        >
          <u-dropdown-item @change="change" title="账本" v-model="bookId" :options="books"></u-dropdown-item>
          <u-dropdown-item
            @change="categoryChange"
            title="类别"
            v-model="categoryId"
            :options="categorys"
          ></u-dropdown-item>
          <u-dropdown-item title="类型" :disabled="categoryId === 0">
            <view class="slot-content" style="background-color: #ffffff">
              <view class="u-flex u-row-center">
                <button class="type-y-btn" @click="selectTypesAll">全部选中</button>
                <button class="type-n-btn" @click="cancelTypesAll">取消全选</button>
              </view>
              <view class="item-box">
                <view
                  class="item"
                  :class="[item.active ? 'active' : '']"
                  @tap="tagClick(index)"
                  v-for="(item, index) in types"
                  :key="index"
                >
                  {{ item.label }}
                </view>
              </view>
            </view>
          </u-dropdown-item>
        </u-dropdown>
      </view>

      <!-- 日历选择 -->
      <u-calendar
        v-model="calendarShow"
        mode="range"
        @change="calendarChange"
        active-bg-color="#19be6b"
        range-color="#19be6b"
        range-bg-color="rgba(25,190,107, 0.13)"
        btn-type="success"
        :default-start-date="startNowDate"
        :default-end-date="endNowDate"
      ></u-calendar>
    </view>

    <view>
      <!-- 汇总金额展示 -->
      <view class="top u-flex u-flex-nowrap">
        <view class="color-orange">当前: {{ amtNowSummary ? amtNowSummary : '0.00' }}</view>
        <view class="color-blue">总: {{ amtSummary ? amtSummary : '0.00' }}</view>
        <view class="color-green">收入: + {{ incomeAmtSummary ? incomeAmtSummary : '0.00' }}</view>
        <view class="color-red">支出: - {{ expenditureAmtSummary ? expenditureAmtSummary : '0.00' }}</view>
      </view>

      <!-- 查询记录列表 -->
      <scroll-view scroll-y class="sv" :style="{ height: navHeight + 'px' }" @scrolltolower="reachBottom">
        <view class="page-box">
          <!-- uView 有问题弃用 -->
          <!-- <u-swipe-action
						class="order"
						v-for="(item, index) in dataList" 
						:key="item.id"
						:index="index"
						@click="click"
						:btn-width="btnWidth"
						:options="options"
					>
						<view class="order-item">
							<view class="left title-wrap">
								<view class="title">{{ item.name }}</view>
								
								<view class="content">
									<view class="type">类型: {{ item.typeName }}</view>
									<view class="other-type">记录时间: {{ item.createTime }}</view>
								</view>
							</view>
							<view class="right title-wrap">
								<view class="expenditure-type" v-if="item.accountCategory == 1">- {{ item.amt }}</view>
								<view class="income-type" v-else>+ {{ item.amt }}</view>
							</view>
						</view>
					</u-swipe-action> -->

					<u-swipe-action v-for="(item, index) in dataList" :key="item.id" :index="index" :options="options" @click="click">
						<view class="order u-border-bottom">
							<view class="order-item">
								<view class="left title-wrap">
									<view class="title">{{ item.name }}</view>

									<view class="content">
										<view class="type">类型: {{ item.typeName }}</view>
										<view class="other-type">记录时间: {{ item.createTime }}</view>
									</view>
								</view>
								<view class="right title-wrap">
									<view class="expenditure-type" v-if="item.accountCategory == 1">- {{ item.amt }}</view>
									<view class="income-type" v-else>+ {{ item.amt }}</view>
								</view>
							</view>
						</view>
					</u-swipe-action>
          <u-loadmore :status="loadStatus" bgColor="#f2f2f2"></u-loadmore>

          <!-- 不需要滑动删除的view -->
          <!-- <view class="order" v-for="(item, index) in dataList" :key="item.id">
						<view class="left">
							<view class="title">{{ item.name }}</view>
						</view>
						<view class="content">
							<view class="expenditure-type" v-if="item.accountCategory == 1">- {{ item.amt }}</view>
							<view class="income-type" v-else>+ {{ item.amt }}</view>
							<view class="type">类型: {{ item.typeName }}</view>
							<view class="type">记录时间: {{ item.createTime }}</view>
						</view>
					</view>
					<u-loadmore :status="loadStatus" bgColor="#f2f2f2"></u-loadmore> -->
        </view>
      </scroll-view>
    </view>

    <!-- 确认删除框 -->
    <Confirm ref="Confirm"></Confirm>
  </view>
</template>

<script>
import Confirm from '@/components/confirm.vue'

export default {
  data() {
    return {
      current: 1,
      size: 20,
      dataList: [
        {
          id: 1,
          name: '下班地铁（交通）',
          amt: '2.48',
          accountCategory: 1
        }
      ],
      name: null,
      incomeAmtSummary: null,
      expenditureAmtSummary: null,
      amtSummary: null,
      amtNowSummary: null,
      loadStatus: 'loadmore',
      pH: 0, //窗口高度
      navHeight: 0, //元素的所需高度
      activeColor: '#19be6b',
      mask: true,
      books: [],
      categorys: [
        {
          label: '全部',
          value: 0
        },
        {
          label: '支出',
          value: 1
        },
        {
          label: '收入',
          value: 2
        }
      ],
      bookId: 1,
      categoryId: 0,
      types: [],
      startNowTime: '',
      endNowTime: '',
      startInput: '',
      endInput: '',
      btnWidth: 150,
      startNowDate: '',
      endNowDate: '',
      options: [
        {
          text: '详情',
          style: {
            backgroundColor: '#007aff'
          }
        },
        {
          text: '删除',
          style: {
            backgroundColor: '#dd524d'
          }
        }
      ],
      calendarShow: false
    }
  },
  components: {
    Confirm
  },
  onUnload() {
    // 移除监听
    uni.$off('refreshPage')
  },
  async onLoad() {
    // 刷新监听
    uni.$on('refreshPage', () => {
      // 执行刷新方法
      this.change()
    })

    this.getNowTime()
    this.getAccountBookList()
    this.getTypeListByCategoryId(this.categoryId)
  },
  onReady() {
    // 动态获取剩余的高度
    var that = this
    uni.getSystemInfo({
      success: function (res) {
        that._data.pH = res.windowHeight //windoHeight为窗口高度，主要使用的是这个
        let titleH = uni.createSelectorQuery().select('.sv') //想要获取高度的元素名（class/id）
        titleH
          .boundingClientRect((data) => {
            let pH = that._data.pH
            that._data.navHeight = pH - data.top //计算高度：元素高度=窗口高度-元素距离顶部的距离（data.top）
          })
          .exec()
      }
    })
  },
  mounted() {},
  methods: {
    // 页面数据
    async getOrderList(current) {
      // 全部默认null
      let categoryId = null
      if (this.categoryId != 0) categoryId = this.categoryId
      let startInput = this.startInput ? this.startInput : this.startNowTime
      let endInput = this.endInput ? this.endInput : this.endNowTime

      let accountCategoryIds = []
      this.types.forEach((type) => {
        if (!type.active) return
        accountCategoryIds.push(type.value)
      })

      // 获取数据
      const params = {
        accountBookId: this.bookId,
        accountCategory: categoryId,
        accountCategoryIds: accountCategoryIds,
        name: this.name,
        startTime: startInput,
        endTime: endInput,
        currentPage: current,
        size: this.size
      }

      const res = await this.$u.api.getAccountRecord(params)
      let data = JSON.parse(JSON.stringify(res.data))

      // 无数据 nomore 页数减回来
      if (data.length == 0) {
        this.loadStatus = 'nomore'
        this.current = --this.current
        return
      }

      if (this.dataList.length == 0) {
        // 赋值
        this.dataList = res.data
      } else {
        // 下拉追加
        data.forEach((item) => {
          this.dataList.push(item)
        })
      }
      this.loadStatus = 'loadmore'
    },
    /**
     * 获取汇总金额数据
     */
    async getAmtSummary() {
      let startInput = this.startInput ? this.startInput : this.startNowTime
      let endInput = this.endInput ? this.endInput : this.endNowTime

      // 获取数据
      const params = {
        accountBookId: this.bookId,
        startTime: startInput,
        endTime: endInput
      }
      const res = await this.$u.api.getAmtSummary(params)
      this.incomeAmtSummary = res.incomeAmtSummary
      this.expenditureAmtSummary = res.expenditureAmtSummary
      this.amtSummary = res.amtSummary
      this.amtNowSummary = res.amtNowSummary
    },
    /**
     * 获取所有的账本信息
     */
    async getAccountBookList() {
      const res = await this.$u.api.getAccountBookList()
      let data = JSON.parse(JSON.stringify(res))

      this.books = []
      data.forEach((item) => {
        let dat = {
          label: item.name,
          value: item.id
        }

        this.books.push(dat)
      })
    },
    async change() {
      // 列表重新查询
      this.dataList = []
      this.current = 1
      this.incomeAmtSummary = null
      this.expenditureAmtSummary = null
      this.amtSummary = null
      this.getOrderList(this.current)
      this.getAmtSummary()
    },
    reachBottom() {
      // 加这个判断 为了防止重复下拉
      if (this.loadStatus != 'loading') {
        // 下拉增加页数
        this.current = ++this.current

        this.loadStatus = 'loading'
        setTimeout(() => {
          this.getOrderList(this.current)
        }, 1200)
      }
    },
    closeDropdown() {
      this.$refs.uDropdown.close()
    },
    closeChange(index) {
      if (index !== 2) return
      this.change()
    },
    /**
     * 根据类别查询类型信息
     * @param {Object} categoryId
     */
    async getTypeListByCategoryId(categoryId) {
      this.types = []

      // 类别为全部 不查询类型
      if (categoryId !== 0) {
        const res = await this.$u.api.getTypesByCategory(categoryId)
        let data = JSON.parse(JSON.stringify(res))

        data.forEach((item) => {
          let dat = {
            label: item.typeName,
            value: item.id,
            active: true
          }

          this.types.push(dat)
        })
      }

      // 列表查询
      this.change()
    },
    tagClick(index) {
      this.types[index].active = !this.types[index].active
    },
    selectTypesAll() {
      this.types.forEach((type) => {
        type.active = true
      })
    },
    cancelTypesAll() {
      this.types.forEach((type) => {
        type.active = false
      })
    },
    async categoryChange() {
      this.getTypeListByCategoryId(this.categoryId)
    },
    /**
     * 日历改变事件
     * @param {Object} e
     */
    calendarChange(e) {
      this.startNowDate = e.startDate
      this.endNowDate = e.endDate
      this.startInput = e.startDate + ' 00:00:00'
      this.endInput = e.endDate + ' 23:59:59'

      this.change()
    },
    /**
     * 获取当前 年月日
     */
    async getNowTime() {
      var dt = new Date()
      let year = dt.getFullYear()
      let month = (dt.getMonth() + 1).toString().padStart(2, '0')
      let date = dt.getDate().toString().padStart(2, '0')
      this.startNowTime = `${year}-${month}-01 00:00:00`
      this.endNowTime = `${year}-${month}-${date} 23:59:59`
      this.startNowDate = `${year}-${month}-01`
      this.endNowDate = `${year}-${month}-${date}`
    },
    /**
     * 查看详情 删除记录
     * @param {Object} index1 按钮下标
     * @param {Object} index 数组下标
     */
    click(index, index1) {
      if (index1 == 1) {
        // 删除
        let id = this.dataList[index].id
        let name = this.dataList[index].name

        this.$refs['Confirm'].open({
          title: '提示',
          content: `是否确定删除 [${name}]?`,
          callback: (action) => {
            if (action == 'sumbit') {
              // 删除记录
              this.$u.api.delAccount(id).then((res) => {
                this.$u.toast('删除成功')

                // 重新查询
                this.change()
              })
            }
          }
        })
      } else {
        let id = this.dataList[index].id
        // 跳转详情页
        this.$u.route({
          type: 'navigateTo',
          url: `/pages/index/account/account_detail?id=${id}`
        })
      }
    },
    /**
     * 跳转新增记录页面
     */
    toAdd() {
      this.$u.route({
        type: 'navigateTo',
        url: '/pages/index/account/account_add'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.slot-content {
  background-color: #ffffff;
  padding: 10rpx 24rpx;

  .type-y-btn {
    border: 1px solid $u-type-primary;
    background-color: $u-type-primary;
    color: #ffffff;
    padding: 0% 10%;
    border-radius: 10rpx;
    font-size: 30rpx;
  }

  .type-n-btn {
    border: 1px solid $u-type-error;
    background-color: $u-type-error;
    color: #ffffff;
    padding: 0% 10%;
    border-radius: 10rpx;
    font-size: 30rpx;
  }

  .item-box {
    margin-bottom: 50rpx;
    display: flex;
    flex-wrap: wrap;
    // justify-content: space-between;

    .item {
      border: 1px solid $u-type-success;
      color: $u-type-success;
      padding: 8rpx 40rpx;
      margin: 0 10rpx;
      border-radius: 100rpx;
      margin-top: 20rpx;
    }

    .active {
      color: #ffffff;
      background-color: $u-type-success;
    }
  }
}

.top {
  margin: 20rpx 40rpx;
  font-size: 24rpx;

  .color-blue {
    color: $u-type-primary;
    margin-right: auto;
    justify-content: flex-start;
  }

  .color-green {
    color: $u-type-success;
    justify-content: center;
  }

  .color-red {
    color: $u-type-error;
    margin-left: auto;
    justify-content: flex-end;
  }

  .color-orange {
    color: orange;
    margin-right: auto;
    justify-content: flex-start;
  }
}

.order {
  width: 710rpx;
  background-color: #ffffff;
  margin: 0 20rpx 0 20rpx;
  border-radius: 20rpx;
  box-sizing: border-box;
  padding: 20rpx;
  font-size: 28rpx;
	display: flex;

  .order-item {
    display: flex;
    justify-content: space-between;

    .left {
      .title {
        margin-right: 20rpx;
        margin-bottom: 20rpx;
        font-size: 35rpx;
        line-height: 45rpx;
      }
    }

    .content {
      .type {
        margin: 6rpx 0;
        font-size: 30rpx;
        color: $u-type-primary;
      }

      .other-type {
        margin: 6rpx 0;
        font-size: 24rpx;
        color: $u-tips-color;
      }
    }

    .right {
      text-align: right;

      .expenditure-type {
        margin-left: 120rpx;
        font-size: 50rpx;
        line-height: 145rpx;
        color: $u-type-error;
      }

      .income-type {
        margin-left: 120rpx;
        font-size: 50rpx;
        line-height: 145rpx;
        color: $u-type-success;
      }
    }
  }
}

.picker-border {
  background-color: #ffffff;
  margin: 0 auto;
  border-radius: 0rpx 0rpx 20rpx 20rpx;
  box-sizing: border-box;
  padding: 20rpx;
  font-size: 28rpx;
}

.swipe-right-item-blue {
  margin: 25rpx auto;
  border-top-left-radius: 20rpx;
  border-bottom-left-radius: 20rpx;
  box-sizing: border-box;
  padding: 20rpx;

  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  float: left;
  height: 180rpx;

  width: 150rpx;
  background-color: #007aff;
  color: #ffffff;
  padding: 20rpx;
  font-size: 35rpx;
}

.swipe-right-item-red {
  margin: 25rpx auto;
  border-top-right-radius: 20rpx;
  border-bottom-right-radius: 20rpx;
  box-sizing: border-box;
  padding: 20rpx;

  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  float: left;
  height: 180rpx;

  width: 150rpx;
  background-color: #dd524d;
  color: #ffffff;
  padding: 20rpx;
  font-size: 35rpx;
}
</style>
